package arrAndstr;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
    219. 存在重复元素 II
 */
public class T219 {
    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3,1,2,3};
        int k = 2;
        System.out.println(containsNearbyDuplicate(nums, k));
    }

    public static boolean containsNearbyDuplicate(int[] nums, int k) {
        // 使用Hash优化
        Map<Integer, Integer> map = new HashMap<>();    // (value, index)

        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], i);
                continue;
            }
            if (map.containsKey(nums[i]) && Math.abs(map.get(nums[i]) - i) <= k) {
                return true;
            }
            map.put(nums[i], i);
        }

        return false;
    }
}
